package com.nananren.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nananren.common.Result;
import com.nananren.domain.Book;
import com.nananren.domain.Category;
import com.nananren.exception.CustomerException;
import com.nananren.mapper.CategoryMapper;
import com.nananren.service.BookService;
import com.nananren.service.CategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.List;

@Service
@Slf4j
public class CategoryServiceImpl extends ServiceImpl<CategoryMapper, Category> implements CategoryService {

    @Autowired
    private CategoryMapper categoryMapper;

    @Autowired
    private BookService bookService;


    // 根据id删除分类信息
    @Override
    @Transactional
    public void deleteWithBook(Long id) {
        // 判断该分类下是否有书籍，如果有，则不允许删除
        LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
        bookLambdaQueryWrapper.eq(Book::getCategoryId, id);
        bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
        // 查询满足条件的图书数量，如果大于0，说明该分类下有图书关联，不能删除！！抛出一个业务异常
        int count = bookService.count(bookLambdaQueryWrapper);
        if (count > 0) {
            throw new CustomerException("当前分类下关联了图书信息，不能删除!!");
        }

        // 正常删除(将is_deleted字段改为0)
        Category category = this.getById(id);
        category.setIsDeleted(0);
        this.updateById(category);
    }

    // 根据ids批量删除分类
    @Override
    @Transactional
    public void deletesWithBook(List<Long> ids) {
        // 遍历每一个id，判断下面是否关联有图书信息
        for (Long id : ids) {
            LambdaQueryWrapper<Book> bookLambdaQueryWrapper = new LambdaQueryWrapper<>();
            bookLambdaQueryWrapper.eq(Book::getCategoryId, id);
            bookLambdaQueryWrapper.eq(Book::getIsDeleted, 1);
            int count = bookService.count(bookLambdaQueryWrapper);
            // count > 0 说明当前分类下有数据关联
            if (count > 0) {
                throw new CustomerException("当前分类下关联了图书信息，不能删除，请自重!!");
            }

            // 根据id获取当前分类
            Category category = this.getById(id);
            // 因为已经判断了ids中的id都是存在的情况，如果再出现null，说明出异常了，需要联系管理员
            if (category == null) {
                throw new CustomerException("出错辣，快联系管理员!!");
            }

            // 没有关联图书，则正常删除
            category.setIsDeleted(0);
            this.updateById(category);
        }
    }
}
